from django.shortcuts import render, HttpResponse

from .models import Book, Author


# Create your views here.
def add_book(request):
    book = Book.objects.create(title='Html', price=20)
    """
        author1 = Author.objects.filter(id=1).first()
        author2 = Author.objects.filter(id=2).first()
        author3 = Author.objects.filter(id=3).first()
        book.authors.add(author1, author2, author3)
    """
    author = Author.objects.create(name='author4', age=25)
    book.authors.add(author)

    return HttpResponse('add book success')


def add_author(request):
    author = Author.objects.filter(id=4).first()  # 4
    book1 = Book.objects.filter(id=1).first()
    book2 = Book.objects.filter(id=2).first()
    # 反向关联
    author.book_set.add(book1, book2)
    return HttpResponse('add author success')


def select_book(request):
    book = Book.objects.filter(id=1).first()
    print('-----------book基本信息-------------')
    print(book.title)
    print(book.price)
    print('-----------book的作者信息-------------')
    authors = book.authors.all()
    for author in authors:
        print(author.name, author.age)
    return HttpResponse('select book success')


def select_author(request):
    author = Author.objects.filter(id=4).first()
    print('-----------作者基本信息-------------')
    print(author.name, author.age)
    print('-----------作者关联的书本信息-------------')
    books = author.book_set.all()
    for book in books:
        print(book.title, book.price)
    return HttpResponse('select author success')


def delete_book(request):
    Book.objects.filter(id=1).delete()
    return HttpResponse('delete book success')


def delete_author(request):
    Author.objects.filter(id=4).delete()
    return HttpResponse('delete Author success')
